//
//  SongStoreViewController.m
//  CloudKaraoke
//
//  Created by BHDMinh on 3/29/14.
//  Copyright (c) 2014 soncamedia. All rights reserved.
//

#import "SongStoreViewController.h"
//#import "ViewLyricViewController.h"
//#import "SoncaIDLoginViewController.h"
//#import "KaraokeViewController.h"
//#import "KaraokeNotification.h"
#import "DisplayCellView.h"
#import "DBInterface.h"
//#import "Playlists.h"
#import "Song.h"

#import "WEPopoverController.h"
#import "ManufacturerViewController.h"
#import "SearchTypeViewController.h"

//#import "XMLParser.h"

@interface SongStoreViewController ()
{
    
}
@end

@implementation SongStoreViewController
//@synthesize optionAlert;
@synthesize manufactureDropDown;
@synthesize searchTypeDropDown;

#pragma mark - Table view data source
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
	return 22;
}

- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    NSInteger songcount = [[self DataForTableView:tableView] count];
    CGRect frame = [self.view bounds];
    UIView * view = [[UIView alloc] initWithFrame:CGRectMake(8.5, 0, frame.size.width, 21.0)];
    [view setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleRightMargin];
    [view setBackgroundColor:KOK_COLOR_WHITE];
    
    UILabel *labelTitle = [[UILabel alloc] initWithFrame:view.frame];
    [labelTitle setText:[NSString stringWithFormat:@"%d bài hát", songcount]];
    [labelTitle setTextColor:KOK_COLOR_LIGHT_BROWN];
    
    [view addSubview:labelTitle];
    
    return view;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [[self DataForTableView:tableView] count];
}

- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [self tableView:tableView cellForRowAtIndexPath:indexPath isExpanded:NO];
}

- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath isExpanded:(BOOL)isExpanded
{
    static NSString *CellIdentifier = @"DisplayCell";
    
    DisplayCellView *cell = (DisplayCellView *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        if ([UIDevice currentDevice].userInterfaceIdiom == UIUserInterfaceIdiomPad) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"DisplayCellViewIPad" owner:self options:nil] objectAtIndex:0];
        }else{
            cell = [[[NSBundle mainBundle] loadNibNamed:@"DisplayCellView" owner:self options:nil] objectAtIndex:0];
        }
    }
    
    Song *song = [[self DataForTableView:tableView] objectAtIndex:indexPath.row];
    [cell setIndexPath:indexPath];
    [cell setDelegate:self];
    [cell setTableView:tableView];
    [cell configureCellForSongObject:song atIndexPath:indexPath withSearchString:searchString andShowFree:[song purchased] inPlaylist:false];
    
    if (!isExpanded) //prepare the cell as if it was collapsed! (without any animation!)
	{
		cell.btnMenu.transform = CGAffineTransformMakeRotation(0);
	}
	else ///prepare the cell as if it was expanded! (without any animation!)
	{
		cell.btnMenu.transform = CGAffineTransformMakeRotation(3.14);
	}
    return cell;
}

- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [self tableView:tableView heightForRowAtIndexPath:indexPath isExpanded:NO];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath isExpanded:(BOOL)isexpanded
{
	if (isexpanded)
		return 99;
	return 55;
}

- (void) tableView:(UITableView *)tableView expandCell:(UITableViewCell *)cell withIndexPath:(NSIndexPath *)indexPath
{
    [UIView animateWithDuration:.5 animations:^{
        DisplayCellView *dCell = (DisplayCellView *) cell;
        [dCell.btnMenu setTransform:CGAffineTransformMakeRotation(3.14)];
	}];
}

-(void) tableView:(UITableView *)tableView collapseCell:(UITableViewCell *)cell withIndexPath:(NSIndexPath *)indexPath
{
    DisplayCellView *dCell = (DisplayCellView *) cell;
    [dCell.btnMenu setTransform:CGAffineTransformMakeRotation(0)];
}

- (void) tableView:(UITableView *) tableView didSelectOnMenuItemAtIndexPath:(NSIndexPath *)indexPath
{
    Song *song = [[self DataForTableView:tableView] objectAtIndex:indexPath.row];
//    if (!optionAlert) {
//        optionAlert = [[ContextPopup alloc] initWithContextType:ContextTypeSong parentView:self andDetail:song];
//    }
//    [optionAlert initPopupContextTypeSong:song];
//    [optionAlert show];
}

- (void) tableView:(UITableView *) tableView didSelectOnFunctionAtIndexPath:(NSIndexPath *)indexPath
{
    Song *song = [[self DataForTableView:tableView] objectAtIndex:indexPath.row];
////    if ([song purchased]) {
//        if([Playlists containSong:song])
//        {
//            [Playlists removeSong:song];
//        }else {
//            [Playlists addSongToPlaylist:song];
//        }
////    }
////    else
////    {
////        SoncaIDLoginViewController *loginView = [[SoncaIDLoginViewController alloc] initWithNibName:@"SoncaIDLoginViewController" bundle:nil];
////        [self.navigationController pushViewController:loginView animated:YES];
////    }
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    Song *aSong = [[self DataForTableView:tableView] objectAtIndex:indexPath.row];
    aSong.favourite = !aSong.favourite;
    
    [[DBInterface instance] updateFavourite:aSong.favourite forSong:aSong];
    [tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationNone];
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (void) tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}

#pragma mark - UIViewHandler
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    appDelegate = [[UIApplication sharedApplication] delegate];
    [self setTitle:@"Danh Sách"];
    
//    [KaraokeNotification registerKaraoke:self notification:KaraokePlaylistChanged selector:@selector(playlistChangedNotificationHandler:)];
//    [KaraokeNotification registerKaraoke:self notification:KaraokeFavouriteChanged selector:@selector(playlistChangedNotificationHandler:)];
    
    [self initSearchHandleBlock];
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.tableViewData setHidden:YES];
    [self.loadingIndicator startAnimating];
    
    [_lblManufacturer setText:@"Vidia Karaoke List"];
    [_lblSearchType setText:@"Bài hát"];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self performSelector:@selector(reloadDisplayData) withObject:nil afterDelay:1.0f];
    if(allData) {
        [self.tableViewData reloadData]; 
        [self.loadingIndicator stopAnimating];
        [self.tableViewData setHidden:NO];
    }
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void) dealloc
{
//    [KaraokeNotification unregisterKaraoke:self notification:KaraokePlaylistChanged];
//    [KaraokeNotification unregisterKaraoke:self notification:KaraokeFavouriteChanged];
    _compareBlock = nil;
    [self.manufactureDropDown dismissPopoverAnimated:NO];
	self.manufactureDropDown = nil;
    
    [searchTypeDropDown dismissPopoverAnimated:YES];
    searchTypeDropDown = nil;
}

#pragma mark - reloadData
- (void) reloadDisplayData
{
    allData = [NSArray arrayWithArray:[[DBInterface instance] querySongForManufaturer:curManufacturer andSearchType:curSearchType partition:curSubType]];
    [tableViewData reloadData];
    [self.loadingIndicator stopAnimating];
    [tableViewData setHidden:NO];
    if ([allData count] > 0) {
        [self.tableViewData scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
    }
}

#pragma mark - songPlaylistHandler
- (void) playlistChangedNotificationHandler:(NSNotification *) notification
{
    [tableViewData reloadData];
    [self updateKaraokeBarButton];
}

- (void) initSearchHandleBlock
{
    _compareBlock = ^SCCompareResult(Song *obj, NSString *searchText) {
        if([obj.shortname rangeOfString:searchText options:NSCaseInsensitiveSearch].location == 0)
        {
            return SCComparePinyin;
        }
        else if([obj.titleRaw rangeOfString:searchText options:NSCaseInsensitiveSearch].location != NSNotFound)
        {
            return SCCompareTitleRaw;
        }else if ([obj.name rangeOfString:searchText options:NSCaseInsensitiveSearch].location != NSNotFound) {
            return SCCompareName;
        }
        return SCCompareNotEqual;
    };
}

- (IBAction)btnManufacturerPresedd:(id)sender {
    if(searchTypeDropDown.isPopoverVisible)
    {
        [searchTypeDropDown dismissPopoverAnimated:YES];
    }
    
    if(manufactureDropDown.isPopoverVisible) return;
    
    if (self.manufactureDropDown == nil) {
		ManufacturerViewController *contentViewController = [[ManufacturerViewController alloc] initWithStyle:UITableViewStylePlain];
		[contentViewController setDelegate:self];
		self.manufactureDropDown = [[WEPopoverController alloc] initWithContentViewController:contentViewController];
        [contentViewController setPopoverController:manufactureDropDown];
        
        NSIndexPath * selectedIndexPath = [NSIndexPath indexPathForRow:curManufacturer inSection:0];
        [contentViewController.tableView selectRowAtIndexPath:selectedIndexPath animated:YES scrollPosition:UITableViewScrollPositionNone];
        [contentViewController.tableView scrollToNearestSelectedRowAtScrollPosition:UITableViewScrollPositionNone animated:YES];
    }
    [self.manufactureDropDown presentPopoverFromRect:_btnManufacture.frame
                                              inView:_btnManufacture
                            permittedArrowDirections:UIPopoverArrowDirectionDown|UIPopoverArrowDirectionUp
                                            animated:YES];
	
}

- (IBAction)btnSearchTypePressed:(id)sender {
    if(manufactureDropDown.isPopoverVisible)
    {
        [manufactureDropDown dismissPopoverAnimated:YES];
    }
    
    if(searchTypeDropDown.isPopoverVisible) return;
    
    if (self.searchTypeDropDown == nil) {
        SearchTypeViewController *contentViewController = [[SearchTypeViewController alloc] initWithStyle:UITableViewStylePlain];
        [contentViewController setDelegate:self];
        [contentViewController setTypeFull:(curManufacturer == MANUFACTURE_VIDIA ? 1 : 0)];
        [contentViewController setCurrentPopoverCellIndex:curSearchType];
        self.searchTypeDropDown = [[WEPopoverController alloc] initWithContentViewController:contentViewController];
        [contentViewController setPopoverController:searchTypeDropDown];
        
        NSIndexPath * selectedIndexPath = [NSIndexPath indexPathForRow:curSearchType inSection:0];
        [contentViewController.tableView selectRowAtIndexPath:selectedIndexPath animated:YES scrollPosition:UITableViewScrollPositionNone];
        [contentViewController.tableView scrollToNearestSelectedRowAtScrollPosition:UITableViewScrollPositionNone animated:YES];
	}
    [self.searchTypeDropDown presentPopoverFromRect:_btnSearchType.frame
                                             inView:_btnSearchType
                           permittedArrowDirections:UIPopoverArrowDirectionDown|UIPopoverArrowDirectionUp
                                           animated:YES];
	
}

- (void) dropDownList:(WEPopoverController *)dropdown didSeletedAtIndex:(NSInteger)index title:(NSString *) title
{
    if (dropdown == nil) return;
    
    if([dropdown isEqual:searchTypeDropDown]) {
        curSearchType = index;
        if (index > SEARCH_TYPE_NHACTRE1T) {
            curSubType = index - SEARCH_TYPE_NHACTRE1T + 1;
        }else {
            curSubType = -1;
        }
        [_lblSearchType setText:title];
    }else if([dropdown isEqual:manufactureDropDown])
    {
        if (curManufacturer == index) {
            return;
        }
        
        if(index != MANUFACTURE_VIDIA && curSearchType >= SEARCH_TYPE_NHACTRE1T)
        {
            curSearchType = SEARCH_TYPE_SONG;
            curSubType = -1;
            [_lblSearchType setText:@"Bài hát"];
        }
        if(index == MANUFACTURE_VIDIA) {
            SearchTypeViewController *contentViewController = [[SearchTypeViewController alloc] initWithStyle:UITableViewStylePlain];
            [contentViewController setDelegate:self];
            [contentViewController setTypeFull:1];
            [contentViewController setCurrentPopoverCellIndex:curSearchType];
            self.searchTypeDropDown = [[WEPopoverController alloc] initWithContentViewController:contentViewController];
            [contentViewController setPopoverController:searchTypeDropDown];
            NSIndexPath * selectedIndexPath = [NSIndexPath indexPathForRow:curSearchType inSection:0];
            [contentViewController.tableView selectRowAtIndexPath:selectedIndexPath animated:YES scrollPosition:UITableViewScrollPositionNone];
            [contentViewController.tableView scrollToNearestSelectedRowAtScrollPosition:UITableViewScrollPositionNone animated:YES];
        }else if(index != curManufacturer && curManufacturer == MANUFACTURE_VIDIA) {
            SearchTypeViewController *contentViewController = [[SearchTypeViewController alloc] initWithStyle:UITableViewStylePlain];
            [contentViewController setDelegate:self];
            [contentViewController setTypeFull:0];
            [contentViewController setCurrentPopoverCellIndex:curSearchType];
            self.searchTypeDropDown = [[WEPopoverController alloc] initWithContentViewController:contentViewController];
            [contentViewController setPopoverController:searchTypeDropDown];
            NSIndexPath * selectedIndexPath = [NSIndexPath indexPathForRow:curSearchType inSection:0];
            [contentViewController.tableView selectRowAtIndexPath:selectedIndexPath animated:YES scrollPosition:UITableViewScrollPositionNone];
            [contentViewController.tableView scrollToNearestSelectedRowAtScrollPosition:UITableViewScrollPositionNone animated:YES];
        }
        curManufacturer = index;
        [_lblManufacturer setText:title];
    }
    
    // Reload display data
    [self reloadDisplayData];
}

@end
